<template>
  <a-cascader
    v-model="cityCode"
    :options="options"
    :field-names="{
      label: 'name',
      value: valueName,
      children: 'children'
    }"
    :getPopupContainer="
      trigger => {
        return trigger.parentNode;
      }
    "
    :show-search="{ filter }"
    expand-trigger="hover"
    placeholder="请选择城市"
    :popupStyle="popupStyle"
    @change="change"
  />
</template>

<script>
import { getCityData } from "@/api/resource";
import { toTree } from "@/util/common";

export default {
  props: {
    value: {
      type: [Array, Number, String]
    },
    // 自定义浮层样式
    popupStyle: {
      type: Object,
      default: () => {
        return {};
      }
    },
    // 返回值的字段
    valueName: {
      type: String,
      default: "id"
    },
    // 返回值是否只有最后一位
    getLastVal: {
      type: Boolean,
      default: false
    },
    // 展示的层级，默认2级（一共3级，省市区）
    getLevel: {
      type: Number,
      default: 2
    }
  },
  data() {
    return {
      options: []
    };
  },
  computed: {
    cityCode: {
      get() {
        return this.value;
      },
      set(n) {
        this.$emit("input", n);
      }
    }
  },
  methods: {
    change(val) {
      this.$emit("input", this.getLastVal ? val[val.length - 1] : val);
      this.$emit("change", this.getLastVal ? val[val.length - 1] : val);
    },
    filter(inputValue, path) {
      return path.some(
        option =>
          option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
      );
    },
    // 根据getLevel处理城市数据
    formatCityData(res) {
      let data = res.filter(i => i.type <= this.getLevel);
      this.options = toTree(data, 0);
    },
    init() {
      getCityData().then(res => {
        this.$storage.s_set("city", res);
        this.formatCityData(res);
      });
    }
  },
  created() {
    let cityData = this.$storage.s_get("city");
    if (cityData) {
      this.formatCityData(cityData);
    } else {
      this.init();
    }
  }
};
</script>
